package com.seecen.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.seecen.utils.IPUtils;
import lombok.extern.log4j.Log4j;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
@Log4j
public class MyInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*System.out.println("走了前置拦截");

        String token = request.getHeader("token");
        if(ObjectUtil.isEmpty(token)) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "请先认证！");
            return false;
        }
        return true;*/
        Map<String, String[]> parameterMap = request.getParameterMap();
        Enumeration<String> parameterNames = request.getParameterNames();
        System.out.println(parameterMap.size());
        while(parameterNames.hasMoreElements()) {
            System.out.println(parameterNames.nextElement());
        }
        String username = request.getParameter("username");
        System.out.println(username);

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("走了后置拦截");
        System.out.println("用户预访问的controller" + handler);
        System.out.println("返回的modelAndView" + modelAndView);
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("走了最终拦截");
//        System.out.println("用户访问的controller" + handler);
//        System.out.println("访问的controller出现异常" + ex);
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        String methodName = handlerMethod.getMethod().getName();
        String ip = IPUtils.getRemoteAddr(request);
        log.info(ip + "在" + DateUtil.formatDateTime(new Date()) + "访问了" + handlerMethod.getBeanType() + "的" + methodName + "方法");
    }


}
